module Gadgets
  class Listbox < Gtk::HBox
    def initialize(name, type, options = {}, &func)
      super()
      options = {:data => [], :scrollable => false, :selection_mode => Gtk::SELECTION_SINGLE}.merge(options)
      @model = Gtk::ListStore.new(*type)
      
      @listbox = Gtk::TreeView.new(@model)
      @listbox.selection.mode = options[:selection_mode]
      @listbox.enable_search = false
      @listbox.headers_visible = false
      
      @listbox.selection.signal_connect('changed') do
        func.call if func
      end
      
      self.add_columns(name, @listbox)
      self.set_data(options[:data])
      if options[:scrollable]
        scrolled_window = Gtk::ScrolledWindow.new
        scrolled_window.add(@listbox)
        self.add(scrolled_window)
      else
        self.add(@listbox)
      end
    end

    def signal_connect(args)
      @listbox.signal_connect(args)
    end
    
    def add_columns(name, treeview)
      renderer = Gtk::CellRendererText.new
      column = Gtk::TreeViewColumn.new(name, renderer, :markup => 0)
      column.sizing = Gtk::TreeViewColumn::FIXED
      column.fixed_width = 50
      treeview.append_column(column)
    end
    
    def clear
      @model.clear
    end
    
    def each
      @model.each do |model, path, iter|
        yield iter
      end
    end
    
    def selected_index
      if @listbox.selection.selected
        @listbox.selection.selected.path.to_str.to_i
      else
        return  -1
      end
    end
    
    def selected_index=(index)
      @listbox.selection.select_path(Gtk::TreePath.new(index))
    end
    
    def selected_item
      return @listbox.selection.selected
    end
    
    def selected_text
      self.selected_item[0]
    end
    
    def selected_data
      return self.selected_item ? self.selected_item[1] : nil
    end
    
    def add_item(name, data)
      iter = @model.append
      iter[0] = name
      iter[1] = data
    end
    
    def delete_selected_items
      while true
        b = false
        @listbox.selection.selected_each do |model, path, iter| 
          break if iter == @last_iter
          b = true;
          @model.remove(iter) 
          break
        end
        break unless b
      end
    end
    
    def set_data(data_arr)
      data_arr.each do |data|
        self.add_item(data[0], data[1])
      end
    end
    
    def select(value)
      iter = @model.iter_first
      return unless iter

      begin
        break if iter[1] == value
      end while iter.next!
      
      if iter
        @listbox.selection.select_iter(iter)
      else
        @listbox.active = 0
      end
    end
  end
end